<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\ValidationCode\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\User\Contract\UserContract;
use MoChat\App\ValidationCode\Logic\StoreLogic;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use Overtrue\EasySms\EasySms;

/**
 * 创建验证码
 *
 * Class Store.
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var StoreLogic
     */
    protected $storeLogic;

    /**
     * @Inject
     * @var UserContract
     */
    protected $user;

    /**
     * @RequestMapping(path="/dashboard/validationCode/store", methods="POST")
     * @return array 返回数组
     */
    public function handle(): array
    {
        # # 参数验证
        $this->validated($this->request->all());

        $captcha = random_int(100000, 999999);

        $params = [
            'phone' => $this->request->input('phone'),
            'type' => $this->request->input('type'),
            'status' => 0,
            'captcha' => $captcha,
            'created_at' => date('Y-m-d H:i:s'),
        ];

        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,

            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => ['aliyun'],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => '/tmp/easy-sms.log',
                ],
                'aliyun' => [
                    'access_key_id' => env('ALIYUN_SMS_ACCESS_ID'),
                    'access_key_secret' => env('ALIYUN_SMS_ACCESS_SECRET'),
                    'sign_name' => env('ALIYUN_SMS_SIGN_NAME'),
                ],
            ],
        ];

        $easySms = new EasySms($config);

        $easySms->send($params['phone'], [
            'content' => sprintf('您的验证码是%s，5分钟内有效。转发他人可能导致账号被盗，请勿泄露，谨防被骗。', $params['captcha']),
            'template' => 'SMS_169870473',
            'data' => [
                'code' => $params['captcha'],
            ],
        ]);

        return $this->storeLogic->handle($params);
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'phone' => 'required | string | size:11 | bail',
            'type' => 'required | integer',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'phone.required' => '手机号码 必填',
            'phone.string' => '手机号码 必需为字符串',
            'phone.size' => '手机号码 字符串长度为固定值：11',
            'type.required' => '验证码类型 必填',
            'type.integer' => '验证码类型 必需为整数',
        ];
    }
}
